<template>
  <div class="login-container">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin">
      <div class="form-group">
        <label for="username">用户名</label>
        <input
            type="text"
            id="username"
            v-model="username"
            placeholder="请输入用户名"
            required
            autocomplete="username"
        />
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input
            type="password"
            id="password"
            v-model="password"
            placeholder="请输入密码"
            required
            autocomplete="current-password"
        />
      </div>
      <button type="button" @click="handleLogin" :disabled="isSubmitting">
        {{ isSubmitting ? '登录中...' : '登录' }}
      </button>
      <p></p>
      <button type="button" @click="handleRegister" :disabled="isSubmitting">
        {{ isSubmitting ? '注册中...' : '注册' }}
      </button>
    </form>
    <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
  </div>
</template>

<script>
import AuthService from '@/services/AuthService'

export default {
  data() {
    return {
      username: "",
      password: "",
      errorMessage: "",
      isSubmitting: false
    }
  },
  methods: {
    async handleRegister() {
      this.isSubmitting = true; // 开始提交，禁用按钮
      this.errorMessage = ''; // 清空错误消息

      try {
        // 调用注册接口
        const response = await AuthService.register(
            this.username,
            this.password
        );

        // 根据返回的 code 进行逻辑处理
        if (response.data.code === 200) {
          alert(response.data.message || "注册成功，请登录！");
          // 清空表单
          this.username = "";
          this.password = "";
        } else {
          this.errorMessage = response.data.message || '注册失败';
        }
      } catch (error) {
        this.handleError(error); // 处理异常
      } finally {
        this.isSubmitting = false; // 提交结束，启用按钮
      }
    },
    async handleLogin() {
      // 清空错误信息
      this.isSubmitting = true; // 开始提交，禁用按钮
      this.errorMessage = ''; // 清空错误消息

      // 前端验证
      if (!this.username || !this.password) {
        this.errorMessage = "用户名和密码不能为空";
        this.isSubmitting = false;
        return;
      }

      try {
        // 调用登录接口
        const response = await AuthService.login(
            this.username,
            this.password
        );

        // 根据返回的 code 进行逻辑处理
        if (response.data.code === 200) {
          // 存储 token 并跳转
          localStorage.setItem('token', response.data.data); // 假设 token 在 data 字段中
          console.log("登录成功，准备跳转到 /chatView");
          this.push()
        } else {
          this.errorMessage = response.data.message || '登录失败';
        }
      } catch (error) {
        this.handleError(error); // 处理异常
      } finally {
        this.isSubmitting = false; // 提交结束，启用按钮
      }
    },
    handleError(error) {
      if (error.response) {
        switch (error.response.status) {
          case 401:
            this.errorMessage = '用户名或密码错误'
            break
          case 500:
            this.errorMessage = '服务器内部错误，请稍后重试'
            break
          default:
            this.errorMessage = `请求失败：${error.response.data.message}`
        }
      } else if (error.request) {
        this.errorMessage = '服务器无响应，请检查网络连接'
      } else {
        this.errorMessage = '请求配置错误'
      }
    }
  }
}

</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 2rem auto;
  padding: 2rem;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  color: #4a5568;
  font-weight: 600;
}

input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
}

input:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 3px rgba(66, 185, 131, 0.1);
}

button {
  width: 100%;
  padding: 0.75rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:disabled {
  background-color: #a0aec0;
  cursor: not-allowed;
}

button:hover:not(:disabled) {
  background-color: #369b6e;
}

.error-message {
  color: #e53e3e;
  margin-top: 1rem;
  text-align: center;
  font-size: 0.9rem;
}
</style>